package com.doumuxie.controller;


import com.doumuxie.utils.ResultUtil;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author doumuxie
 * @version 1.0
 * @date 2020/2/7 11:06
 * @description 控制层
 **/
@RestController
public class AuthController {


    @RequestMapping("/loginSuccess")
    public ResultUtil loginSuccess() {
        return ResultUtil.success(getUsername() + "欢迎！");
    }

    @GetMapping("/r/r1")
    @PreAuthorize("hasAnyAuthority('r1')")
    public ResultUtil r1() {
        return ResultUtil.success(getUsername() + "访问资源r1");
    }

    @GetMapping("/r/r2")
    @PreAuthorize("hasAnyAuthority('r2')")
    public ResultUtil r2() {
        return ResultUtil.success(getUsername() + "访问资源r2");
    }

    public String getUsername() {
        // 当前用户身份
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        if (principal == null) {
            return "匿名";
        }
        if (principal instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) principal;
            return userDetails.getUsername();
        }
        return principal.toString();
    }

}
